package com.zijie.shoprbacapi.api;


import com.zijie.core.util.JsonResult;
import com.zijie.rbac.model.RolePermMapping;
import com.zijie.rbac.service.RolePermMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 功能：
 *
 * @author 臧金玉
 * <p>
 * <p>
 * Created by 臧金玉 on 2025/5/9 11:11, Modified by 臧金玉 on 2025/5/9 11:11
 */
@RestController
@RequestMapping(value = "/api/v1/role_perms", produces = MediaType.APPLICATION_JSON_VALUE)
public class RolePermMappingApi {
    private RolePermMappingService rolePermMappingService;

    @Autowired
    public void setRolePermMappingService(RolePermMappingService rolePermMappingService) {
        this.rolePermMappingService = rolePermMappingService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> findAll(RolePermMapping rpm) {
        List<RolePermMapping> mappings = rolePermMappingService.findAll(rpm);
        return ResponseEntity.ok(JsonResult.success(mappings));
    }

    @GetMapping("/id/{id}")
    public ResponseEntity<JsonResult<?>> findById(@PathVariable("id") Integer id) {
        RolePermMapping rpm = rolePermMappingService.findById(id);
        if (rpm == null) {
            return ResponseEntity.ok(JsonResult.error("未查询到指定编号的角色-权限关联"));
        } else {
            return ResponseEntity.ok(JsonResult.success(rpm));
        }
    }

    @PostMapping("/save")
    public ResponseEntity<JsonResult<?>> save(@RequestBody RolePermMapping rpm) {
        boolean success = rolePermMappingService.save(rpm);
        if (success) {
            return ResponseEntity.ok(JsonResult.success("保存成功"));
        } else {
            return ResponseEntity.ok(JsonResult.error("保存角色-权限关联失败"));
        }
    }

    @PutMapping("/update")
    public ResponseEntity<JsonResult<?>> update(@RequestBody RolePermMapping rpm) {
        boolean success = rolePermMappingService.update(rpm);
        if (success) {
            return ResponseEntity.ok(JsonResult.success("修改成功"));
        } else {
            return ResponseEntity.ok(JsonResult.error("修改角色-权限关联失败"));
        }
    }

    @DeleteMapping("/delete")
    public ResponseEntity<JsonResult<?>> deleteByIds(@RequestBody Integer[] ids) {
        int count = rolePermMappingService.deleteByIds(List.of(ids));
        if (count > 0) {
            return ResponseEntity.ok(JsonResult.success(count));
        } else {
            return ResponseEntity.ok(JsonResult.error("删除角色-权限关联失败"));
        }
    }
}
